/*
 * @Author: kanglang
 * @Date: 2020-11-23 19:16:17
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-06 14:29:41
 * @Description: 设置密码
 */

import React, { Component } from 'react';
import { StyleSheet, View, Text, SafeAreaView, NativeModules } from 'react-native';
import { msg, ValidConst, cache, AsyncStorage, SyncStorage } from '@/common';
import { px2dp, fontColorBlack, fontColorSecDeepGray, isAndroid } from '@/styles';
import user from '@/api/user';
import LoginBtn from '../components/login-btn';
import XmInput from '../components/xm-input';

const CookieManager = NativeModules.RNCookieManagerIOS;

export default class SetPassword extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password: '',
      confirmPassword: '',
    };
  }

  render() {
    const { password, confirmPassword } = this.state;
    const isActive = (password !== '' && confirmPassword !== '');
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.inner}>
          <View style={styles.upPart}>
            <View style={{ paddingHorizontal: px2dp(24) }}>
              <Text style={styles.setPwd}>设置密码</Text>
              <Text style={styles.tips}>密码需由 6-12 位数字或字母组成</Text>
            </View>
            <View style={styles.secondPart}>
              <View style={styles.pwdWrap}>
                <XmInput
                  name='password'
                  isPwd
                  placeholder='请输入密码'
                  onChange={this.onChangeText}
                />
              </View>
              <View style={styles.pwdWrap}>
                <XmInput
                  name='confirmPassword'
                  isPwd
                  placeholder='再次确认密码'
                  onChange={this.onChangeText}
                />
              </View>
            </View>

          </View>
          <LoginBtn
            disabled={!isActive}
            isActive={isActive}
            btnText={routerFrom == 'setPwd' ? '提交' : '完成并登录'}
            submit={this.finish}
          />
        </View>

      </SafeAreaView>
    );
  }

  onChangeText = (name, value) => {
    this.setState({ [name]: value });
  }

  // 去设置密码
  finish = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { mobile, routerFrom } = params;
    const { password, confirmPassword } = this.state;
    const regexPassword = ValidConst.password;
    if (!regexPassword.test(password)) {
      msg.emit('app:tip', { text: '密码格式输入不正确' });
      return;
    }
    if (!regexPassword.test(confirmPassword)) {
      msg.emit('app:tip', { text: '确认密码输入格式不正确' });
      return;
    }
    if (password !== confirmPassword) {
      msg.emit('app:tip', { text: '两次输入的密码不一致' });
      return;
    }
    if (routerFrom == 'setPwd') { // 个人中心设置密码
      user.updateLoginPwd({ password }).then(res => {
        if (res.success) {
          msg.emit('router: goToNext', {
            routeName: 'AccountCenter'
          });
        } else {
          msg.emit('app:tip', { text: res.msg });
          msg.emit('router: goToNext', {
            routeName: 'AccountCenter'
          });
        }
      });
    } else {
      user.rebuildPwd({ mobile, password }).then(res => {
        if (res.success) {
          // user.getUserInfo().then(res => {
          //   if (res.success) {
          //     AsyncStorage.setItem(cache.USER_INFO, res.data);
          //     const Role = SyncStorage.getItem(cache.ROLE);
          //     this.goToRoleApp(Role);
          //   } else {
          //     msg.emit('app:tip', { text: res.msg });
          //   }
          // });
          msg.emit('router: goToNext', {
            routeName: 'LoginView',
          });
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      });
    }
  };

  // 角色判断，不同角色进入不同app
  goToRoleApp = (role) => {
    if (!role) {
      msg.emit('router: reset', {
        routeName: 'RoleSwitch',
      });
      return;
    }
    // 司机：driver  车主：car_owner  货主：goods_owner
    if (role === 'driver') {
      msg.emit('router: reset', {
        routeName: 'DriverTab',
      });
    } else if (role === 'car_owner') {
      msg.emit('router: reset', {
        routeName: 'CarOwnerTab',
      });
    } else if (role === 'goods_owner') {
      msg.emit('router: reset', {
        routeName: 'GoodsOwnerTab',
      });
    }
  };
}

const styles = StyleSheet.create({
  inner: {
    flex: 1,
    alignItems: 'center'
  },
  upPart: {
  },
  setPwd: {
    color: fontColorBlack,
    fontSize: px2dp(48),
    marginTop: px2dp(102)
  },
  tips: {
    color: fontColorSecDeepGray,
    fontSize: px2dp(28),
    marginTop: px2dp(8)
  },
  secondPart: {
    width: '100%',
    marginTop: px2dp(48),
  },
  pwdWrap: {
    width: '100%',
    marginTop: px2dp(20),
  },
});
